<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
        <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-house" style="font-weight: bold">&nbsp;&nbsp;后台管理</i>
        </el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-s-marketing">&nbsp;&nbsp;用户管理</i></el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-s-order">&nbsp;&nbsp;用户列表</i></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="data-canRead" style="width: 100%;background-color: white;height: auto">
      <el-divider content-position="left">用户查询</el-divider>
      <el-form ref="form">
        <el-row style="vertical-align:bottom;">
          <el-col :span="1">&nbsp;</el-col>
          <el-col :span="8" style="display:inline-block;">
            <el-form-item>
              <span style="font-size: 18px;float: left">搜索用户&nbsp;</span>
              <el-input v-model="inputName" placeholder="请输入用户名称" style="width: 500px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="admin.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="100px" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" width="100px" align="center"></el-table-column>
        <el-table-column prop="nickname" label="用户昵称" width="100px" align="center"></el-table-column>
        <el-table-column label="用户头像" width="100px" align="center">
          <template slot-scope="scope">
            <el-avatar :size="50" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="110"
                         align="center"></el-table-column>
        <el-table-column prop="email" label="电子邮箱" width="300" :show-overflow-tooltip="true"
                         align="center"></el-table-column>
        <el-table-column prop="description" label="用户简介" width="500px" align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否启用" width="100px" align="center">
          <template slot-scope="scope">
            <el-switch
                @change="updateEnable(scope.row)"
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#999">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否启用经理" width="100px" align="center">
          <template slot-scope="scope">
            <el-switch
                @change="updateManager(scope.row)"
                v-model="scope.row.manager"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#999">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                circle
                v-if="display==0"
                @click="handleEdit(scope.row)"><i class="el-icon-edit" style="color: white"></i>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                circle
                @click="openDeleteConfirm(scope.row)"><i class="el-icon-delete" style="color: white"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:15px;">
        <el-pagination align='center' @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="[1,5,10,20]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="admin.length">
        </el-pagination>
      </div>
    </div>
    <!--修改用户弹出的对话框-->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisible" append-to-body>
      <el-form :model="adminForm" :rules="rules" :ref="adminForm">
        <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="nickname">
          <el-input v-model="adminForm.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户简介" :label-width="formLabelWidth" prop="description">
          <el-input v-model="adminForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="adminForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth" prop="email">
          <el-input v-model="adminForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="avatar">
          <el-input v-model="adminForm.avatar" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdminFrom()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '120px',
      display: 0,
      adminOptions: [],
      admin: [],
      adminN: [],
      inputName: '',
      adminForm: {
        phone: '',
        description: '',
        nickname: '',
        email: '',
        avatar: ''
      },
      rules: {
        nickname: [
          {required: true, message: "请输入用户昵称", trigger: 'blur'},
          {pattern: /([\u4E00-\u9FA5])+/, message: "请输入中文", trigger: 'blur'}
        ],
        description: [
          {required: true, message: "请输入用户简介", trigger: 'blur'},
          {
            pattern: /([\u4E00-\u9FA5])+([\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c])*/,
            message: "请输入中文",
            trigger: 'blur'
          }
        ],
        phone: [
          {required: true, message: "请输入用户电话", trigger: 'blur'},
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "请输入正确的电话格式",
            trigger: 'blur'
          }
        ],
        avatar: [
          {required: true, message: "请输入用户头像地址", trigger: 'blur'},
        ],
        email: [
          {required: true, message: "请输入用户邮箱", trigger: 'blur'},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "请输入正确邮箱格式", trigger: 'blur'}
        ],
      },
      currentPage: 1,
      pageSize: 10,
    }
  },
  methods: {
    /*加载用户*/
    loadAdminNList() {
      let url = 'http://localhost:9090/admins';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.adminOptions = responseBody.data;
          this.admin = responseBody.data;
          this.adminN = this.admin;
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    /*查询角色明细*/
    searchName(keywords) {
      return this.admin.filter(item => {
        if (item.nickname.includes(keywords)) {
          return item
        }
      })
    },
    /*弹出修改用户窗口*/
    handleEdit(admin) {
      let url = 'http://localhost:9090/admins/' + admin.nickname;
      console.log('name=' + admin.nickname);
      console.log('url' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        console.log('state=' + responseBody.state);
        if (responseBody.state == 20000) {
          this.dialogFormVisible = true;
          this.adminForm = responseBody.data;
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },
    /*修改用户的窗口*/
    submitAdminFrom(){
      let url = 'http://localhost:9090/admins/' + this.adminForm.id + '/update';
      console.log('url' + url);
      let formData = this.qs.stringify(this.adminForm);
      console.log('formData=' + formData)

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            type: 'success',
            message: '修改用户成功!'
          });
          this.dialogFormVisible = false;
          this.loadAdminNList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadAdminNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },
    /*弹出用户删除窗口*/
    openDeleteConfirm(admin) {
      let title = '提示';
      let message = '此操作将永久删除【' + admin.nickname + '】用户, 是否继续?';
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(admin);
      }).catch(() => {
      });
    },
    /*用户删除窗口*/
    handleDelete(admin) {
      let url = 'http://localhost:9090/admins/' + admin.id + '/delete';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '删除用户【' + admin.nickname + '】成功！',
            type: 'success'
          });
          this.loadAdminNList();
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminNList();
            }
          });
        }
      });
    },
    /*是否启用*/
    updateEnable(admin) {
      let enableStatus = [
        {'url': '/disable', text: '禁用'},
        {'url': '/enable', text: '启用'}
      ];
      let url = 'http://localhost:9090/admins/'
          + admin.id + enableStatus[admin.enable].url;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: enableStatus[admin.enable].text + '用户成功！',
            type: 'success'
          });
          this.loadAdminNList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    /*是否启用经理*/
    updateManager(admin) {
      let managerStatus = [
        {'url': '/nomanager', text: '禁用'},
        {'url': '/manager', text: '启用'}
      ];
      let url = 'http://localhost:9090/admins/'
          + admin.id + managerStatus[admin.manager].url;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: managerStatus[admin.manager].text + '经理成功！',
            type: 'success'
          });
          this.loadAdminNList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    /*表格*/
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
  },
  mounted() {
    this.loadAdminNList();
  },
  watch: {
    inputName: function (val) {
      if (val == '') {
        this.admin = this.adminN
      } else {
        this.admin = this.searchName(val)
      }
    }
  }
}
</script>

<style scoped>
* {
  color: black;
}

.data-canRead {
  width: 380px;
  height: 380px;
  margin-top: 15px;
  box-shadow: 0px 5px 5px #8d858a;
  float: left;
  margin-right: 16px;
}

.dept_formSubmit_search {
  width: 200px;
  float: left;
  right: 10px;
  background-color: white;
}

</style>